<script setup lang="ts">
import { ref, watch } from 'vue';
import { ElDialog, ElForm, ElFormItem, ElInput, ElButton } from 'element-plus';
import { $t } from '@vben/locales';

const props = defineProps({
  modelValue: { type: Boolean, required: true },
  formData: { type: Object, default: () => ({ name: '', pid: undefined }) },
  mode: { type: String, default: 'add' }, // 'add' or 'edit'
  parentTreeOptions: { type: Array, default: () => [] }, // 父级树形下拉选项
  loadFlag: { type: Boolean, default: false },
});

const emit = defineEmits(['update:modelValue', 'confirm', 'cancel']);

const localForm = ref({ name: '', pid: undefined });
const formRef = ref();
const rules = {
  name: [
    { required: true, message: $t('common.inputPhTxt', [$t('subject.subjectName')]), trigger: 'blur' },
  ],
};

watch(() => props.formData, (val: any) => {
  localForm.value = { ...val };
}, { immediate: true });

const handleConfirm = () => {
  formRef.value.validate((valid: boolean) => {
    if (valid) {
      emit('confirm', { ...localForm.value });
    }
  });
};
const handleCancel = () => {
  // 清空表单内容和校验
  formRef.value?.resetFields && formRef.value.resetFields();
  emit('update:modelValue', false);
  emit('cancel');
};
</script>
<template>
  <ElDialog
    :model-value="modelValue"
    :title="mode === 'add' ? $t('subject.addSubject') : $t('subject.editSubject')"
    width="500px"
    @close="handleCancel"
    align-center
  >
    <ElForm ref="formRef" :model="localForm" :rules="rules" label-width="90px">
      <ElFormItem :label="$t('subject.subjectName')" prop="name">
        <ElInput v-model="localForm.name" :placeholder='$t("common.inputPhTxt")' maxlength="50" />
      </ElFormItem>
      <ElFormItem :label="$t('subject.superSubject')" prop="pid">
        <el-tree-select
          v-model="localForm.pid"
          :data="parentTreeOptions"
          check-strictly
          :render-after-expand="false"
          show-checkbox
          check-on-click-node
          style="width: 100%"
          :placeholder='$t("common.selectPhTxt")'
        />
      </ElFormItem>
    </ElForm>
    <template #footer>
      <ElButton @click="handleCancel">{{ $t('common.cancelTxt') }}</ElButton>
      <ElButton type="primary" @click="handleConfirm" :loading="loadFlag">{{ $t('common.confirm') }}</ElButton>
    </template>
  </ElDialog>
</template>
